"""
租户配置管理API
"""
from flask import request, jsonify, g
from flask_jwt_extended import jwt_required
from app.api.v1.admin import admin_blueprint
from app.models.tenant_config import TenantConfig, TenantConfigService, ConfigTypes, PREDEFINED_CONFIGS
from app.core.extensions import db


@admin_blueprint.route('/tenant-configs', methods=['GET'])
@jwt_required()
def get_tenant_configs():
    """获取当前租户的所有配置"""
    try:
        tenant_id = getattr(g, 'tenant_id', 1)
        config_type = request.args.get('config_type')

        configs = TenantConfigService.get_all_configs(tenant_id, config_type)

        return jsonify({
            'code': 0,
            'message': '获取成功',
            'data': {
                'configs': configs,
                'predefined': PREDEFINED_CONFIGS
            }
        })
    except Exception as e:
        return jsonify({'code': 1, 'message': f'获取配置失败: {str(e)}'}), 500


@admin_blueprint.route('/tenant-configs', methods=['POST'])
@jwt_required()
def set_tenant_config():
    """设置租户配置"""
    try:
        data = request.get_json()
        tenant_id = getattr(g, 'tenant_id', 1)

        config_type = data.get('config_type')
        config_key = data.get('config_key')
        config_value = data.get('config_value')
        description = data.get('description')
        is_encrypted = data.get('is_encrypted', False)

        if not all([config_type, config_key]):
            return jsonify({'code': 1, 'message': '配置类型和键名不能为空'}), 400

        config = TenantConfigService.set_config(
            tenant_id, config_type, config_key, config_value, description, is_encrypted
        )

        # 清除缓存
        from app.services.tenant_config_service import get_tenant_config
        get_tenant_config().clear_cache(tenant_id)

        return jsonify({
            'code': 0,
            'message': '设置成功',
            'data': config.to_dict()
        })
    except Exception as e:
        return jsonify({'code': 1, 'message': f'设置配置失败: {str(e)}'}), 500


@admin_blueprint.route('/tenant-configs/batch', methods=['POST'])
@jwt_required()
def set_tenant_configs_batch():
    """批量设置租户配置"""
    try:
        data = request.get_json()
        tenant_id = getattr(g, 'tenant_id', 1)
        configs = data.get('configs', [])

        if not configs:
            return jsonify({'code': 1, 'message': '配置列表不能为空'}), 400

        results = []
        for config_data in configs:
            config_type = config_data.get('config_type')
            config_key = config_data.get('config_key')
            config_value = config_data.get('config_value')
            description = config_data.get('description')
            is_encrypted = config_data.get('is_encrypted', False)

            if not all([config_type, config_key]):
                continue

            config = TenantConfigService.set_config(
                tenant_id, config_type, config_key, config_value, description, is_encrypted
            )
            results.append(config.to_dict())

        # 清除缓存
        from app.services.tenant_config_service import get_tenant_config
        get_tenant_config().clear_cache(tenant_id)

        return jsonify({
            'code': 0,
            'message': f'批量设置成功，共设置{len(results)}项配置',
            'data': results
        })
    except Exception as e:
        return jsonify({'code': 1, 'message': f'批量设置配置失败: {str(e)}'}), 500


@admin_blueprint.route('/tenant-configs/<int:config_id>', methods=['DELETE'])
@jwt_required()
def delete_tenant_config(config_id):
    """删除租户配置"""
    try:
        tenant_id = getattr(g, 'tenant_id', 1)

        config = TenantConfig.query.filter_by(id=config_id, tenant_id=tenant_id).first()
        if not config:
            return jsonify({'code': 1, 'message': '配置不存在'}), 404

        db.session.delete(config)
        db.session.commit()

        # 清除缓存
        from app.services.tenant_config_service import get_tenant_config
        get_tenant_config().clear_cache(tenant_id)

        return jsonify({'code': 0, 'message': '删除成功'})
    except Exception as e:
        return jsonify({'code': 1, 'message': f'删除配置失败: {str(e)}'}), 500


@admin_blueprint.route('/tenant-configs/types', methods=['GET'])
@jwt_required()
def get_config_types():
    """获取配置类型列表"""
    try:
        types = {
            ConfigTypes.WECHAT_MP: '微信小程序',
            ConfigTypes.WECHAT_PAY: '微信支付',
            ConfigTypes.WECHAT_GZH: '微信公众号',
            ConfigTypes.DOUBAO_AI: '豆包AI',
            ConfigTypes.SYSTEM: '系统配置',
            ConfigTypes.CUSTOM: '自定义配置',
            ConfigTypes.TCOS: ' 腾讯云对象存储'
        }

        return jsonify({
            'code': 0,
            'message': '获取成功',
            'data': {
                'types': types,
                'predefined': PREDEFINED_CONFIGS
            }
        })
    except Exception as e:
        return jsonify({'code': 1, 'message': f'获取配置类型失败: {str(e)}'}), 500


@admin_blueprint.route('/tenant-configs/test/<config_type>', methods=['POST'])
@jwt_required()
def test_tenant_config(config_type):
    """测试租户配置"""
    try:
        tenant_id = getattr(g, 'tenant_id', 1)

        if config_type == ConfigTypes.WECHAT_MP:
            # 测试微信小程序配置
            app_id = TenantConfigService.get_config(tenant_id, config_type, 'app_id')
            app_secret = TenantConfigService.get_config(tenant_id, config_type, 'app_secret')

            if not app_id or not app_secret:
                return jsonify({'code': 1, 'message': '微信小程序配置不完整'})

            # 这里可以添加实际的API测试逻辑
            return jsonify({'code': 0, 'message': '微信小程序配置测试通过'})

        elif config_type == ConfigTypes.DOUBAO_AI:
            # 测试豆包AI配置
            api_key = TenantConfigService.get_config(tenant_id, config_type, 'api_key')
            base_url = TenantConfigService.get_config(tenant_id, config_type, 'base_url')

            if not api_key or not base_url:
                return jsonify({'code': 1, 'message': '豆包AI配置不完整'})

            # 这里可以添加实际的API测试逻辑
            return jsonify({'code': 0, 'message': '豆包AI配置测试通过'})

        elif config_type == ConfigTypes.TCOS:
            # 测试腾讯云COS配置
            secret_id = TenantConfigService.get_config(tenant_id, config_type, 'secret_id')
            secret_key = TenantConfigService.get_config(tenant_id, config_type, 'secret_key')
            region = TenantConfigService.get_config(tenant_id, config_type, 'region')
            bucket = TenantConfigService.get_config(tenant_id, config_type, 'bucket')

            if not all([secret_id, secret_key, region, bucket]):
                return jsonify({'code': 1, 'message': '腾讯云COS配置不完整'})

            try:
                # 测试COS连接
                from qcloud_cos import CosConfig, CosS3Client
                config = CosConfig(
                    Region=region,
                    SecretId=secret_id,
                    SecretKey=secret_key,
                    Token=None,
                    Scheme='https'
                )
                client = CosS3Client(config)

                # 测试获取存储桶信息
                response = client.head_bucket(Bucket=bucket)
                return jsonify({'code': 0, 'message': '腾讯云COS配置测试通过'})

            except Exception as cos_e:
                return jsonify({'code': 1, 'message': f'腾讯云COS连接失败: {str(cos_e)}'})

        else:
            return jsonify({'code': 1, 'message': '不支持的配置类型'})

    except Exception as e:
        return jsonify({'code': 1, 'message': f'测试配置失败: {str(e)}'}), 500
